#include "clientwidget.h"
#include "ui_clientwidget.h"
#include<QMessageBox>
#include<QHostAddress>
ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);

    tcpSocket = new QTcpSocket(this);

    isStart = true;
    ui->progressBar->setValue(0);//当前值

    connect(tcpSocket,&QTcpSocket::readyRead,
            [=]()
            {
               //取出接收的内容
                QByteArray buf = tcpSocket->readAll();

                if(isStart == true)//接受的是头部信息
                {
                   isStart = false;
                   //解析头部信息 QString buf = "hello##1024"
                   //初始化
                   fileName = QString(buf).section("##",0,0);
                   fileSize = QString(buf).section("##",1,1).toInt();
                   recvSize = 0;

                   //打开文件
                   file.setFileName(fileName);//为什么服务器里不这么写

                   bool isOK = file.open(QIODevice::WriteOnly);
                   if(isOK == false)
                   {
                       qDebug() << "只写出错";
                   }

                   //显示接收文件的信息
                   QString str = QString("接收文件大小：[%1: %2Mb]").arg(fileName).arg(fileSize/1024/1024);
                   ui->textEdit->append(str);

                   //设置进度条
                   ui->progressBar->setMinimum(0);
                   ui->progressBar->setMaximum(fileSize/1024);


                }
                else
                {
                    qint64 len = file.write(buf);
                    recvSize += len;

                    ui->progressBar->setValue(recvSize/1024);//更新进度条

                    if(recvSize == fileSize)
                    {
                        file.close();
                        QMessageBox::information(this,"完成","文件接收完成");

                        tcpSocket->disconnectFromHost();
                        tcpSocket->close();
                    }
                }
            }
            );

}

ClientWidget::~ClientWidget()
{
    delete ui;
}

void ClientWidget::on_pushButton_clicked()
{
    //获取服务器ip和端口
    QString ip = ui->lineEditIP->text();
    quint16 port = ui->lineEditPort->text().toUShort();

    tcpSocket->connectToHost(QHostAddress(ip),port);
}
